package thread;

import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
import midlets.ConexaoWebServer;
import org.ksoap.SoapObject;
import org.ksoap.transport.HttpTransport;
import util.Constantes;
import entidades.Usuario;



public class ThreadEnviaBackUpWebService extends Thread{
	
	
	private String dadosFormatados;
	private String servicoWebService;
	private Usuario usuario;
	private CommandListener commandListener;
	
	
	
	public ThreadEnviaBackUpWebService(CommandListener commandListener, MIDlet midlet,
			String dadosFormatados, String servicoWebService, Usuario usuario) {

		
		if (ConexaoWebServer.display == null) {
			ConexaoWebServer.display = Display.getDisplay(midlet);
		}
		
		ConexaoWebServer.alert1 = new Alert("Conectando", "Aguarde...", null, AlertType.INFO);
		
		ConexaoWebServer.c_sair = new Command("Sair", Command.ITEM, 1);
		ConexaoWebServer.c_sim1  = new Command("Sim", Command.ITEM, 2);
		
		ConexaoWebServer.display.setCurrent(ConexaoWebServer.alert1);
		ConexaoWebServer.alert1.setTimeout(Alert.FOREVER);
		
		this.commandListener = commandListener;
		this.dadosFormatados = dadosFormatados;
		this.servicoWebService = servicoWebService;
		this.usuario = usuario;
		
	}
	
	
	
	public void run() {

		try {
			
			SoapObject client = new SoapObject(ConexaoWebServer.URL, this.servicoWebService);
			client.addProperty("dados", this.dadosFormatados);
			client.addProperty("nomeUsuario", this.usuario.getNome());
			client.addProperty("senha", this.usuario.getSenha());
			client.addProperty("codigoacesso", new Long(this.usuario.getCodigoAcesso()));

			HttpTransport ht = new HttpTransport(ConexaoWebServer.URL,this.servicoWebService);

			String retornoDados = (String) ht.call(client);
			
			if (retornoDados.equalsIgnoreCase("TRUE")) {

				ConexaoWebServer.alert1.setString(Constantes.SUCESSO_ENVIO_BACKUP);
				
			} else {
				
				ConexaoWebServer.alert1.setString(retornoDados);
			}
			
			ConexaoWebServer.alert1.addCommand(ConexaoWebServer.c_sair);
			ConexaoWebServer.alert1.removeCommand(ConexaoWebServer.c_sim1);
			ConexaoWebServer.alert1.setCommandListener(this.commandListener);
			
		} catch(ConnectionNotFoundException e){
			
			e.printStackTrace();
			ConexaoWebServer.alert1.setString(Constantes.FALHA_CONEXAO_WEBSERVICE);

			ConexaoWebServer.alert1.addCommand(ConexaoWebServer.c_sim1);
			ConexaoWebServer.alert1.addCommand(ConexaoWebServer.c_sair);
			ConexaoWebServer.alert1.setCommandListener(this.commandListener);
			
		}
		
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
}// fim da classe.
